#!/bin/sh -e

APP_BINARY=${1}
EXTRA_LIBS=${2}
PACKAGE_SOURCE_DIR=${3}

echo "build-apk configuration:
- APP_BINARY(1)=${APP_BINARY}
- EXTRA_LIBS(2)=${EXTRA_LIBS}
- PACKAGE_SOURCE_DIR(3)=${PACKAGE_SOURCE_DIR}

- ANDROID_NDK_ROOT=${ANDROID_NDK_ROOT}
- ANDROID_SDK_ROOT=${ANDROID_SDK_ROOT}
- QT_ANDROID=${QT_ANDROID}
- ANDROID_NDK_HOST=${ANDROID_NDK_HOST}
- ANDROID_NDK_TOOLCHAIN_ABI=${ANDROID_NDK_TOOLCHAIN_ABI}
- ANDROID_SDK_BUILD_TOOLS=${ANDROID_SDK_BUILD_TOOLS}
"
[ -f "${APP_BINARY}" ] || exit 1
[ "${EXTRA_LIBS}" ] || exit 2
[ "${PACKAGE_SOURCE_DIR}" ] || exit 3

[ -d "${ANDROID_NDK_ROOT}" ] || exit 0
[ -d "${ANDROID_SDK_ROOT}" ] || exit 0
[ -d "${QT_ANDROID}" ] || exit 0
[ "${ANDROID_NDK_HOST}" ] || exit 0
[ "${ANDROID_NDK_TOOLCHAIN_ABI}" ] || exit 0
[ "${ANDROID_SDK_BUILD_TOOLS}" ] || exit 0

build_libs="android-build/libs/${ANDROID_NDK_TOOLCHAIN_ABI}"
mkdir -p "${build_libs}"
cp -fl "${APP_BINARY}" "${build_libs}"

# Create deployment json configuration
cat > android_deployment_settings.json <<EOF
{
  "application-binary": "${APP_BINARY}",
  "android-extra-libs": "${EXTRA_LIBS}",
  "android-package-source-directory": "${PACKAGE_SOURCE_DIR}",
  "description": "This file is generated by CMake to be read by androiddeployqt and should not be modified by hand.",
  "ndk": "${ANDROID_NDK_ROOT}",
  "ndk-host": "${ANDROID_NDK_HOST}",
  "qt": "${QT_ANDROID}",
  "sdk": "${ANDROID_SDK_ROOT}",
  "sdkBuildToolsRevision": "${ANDROID_SDK_BUILD_TOOLS}",
  "stdcpp-path": "${ANDROID_NDK_ROOT}/sources/cxx-stl/llvm-libc++/libs/${ANDROID_NDK_TOOLCHAIN_ABI}/libc++_shared.so",
  "target-architecture": "${ANDROID_NDK_TOOLCHAIN_ABI}",
  "tool-prefix": "llvm",
  "toolchain-prefix": "llvm",
  "useLLVM": true
}
EOF

"${QT_ANDROID}/bin/androiddeployqt" --gradle --input android_deployment_settings.json --output android-build --android-platform ${ANDROID_NDK_PLATFORM}
